import queryString from "query-string";
import config, { isDev } from "../config";
import { useAuthStore } from '../store/useAuthStore';
import { CacheAuthrizedToken } from "../utils/cache";
import navigator from "../utils/navigator";
import { isExternal } from "../utils/validator";
import { getCurrentInstance } from "vue";
  
  let isRedirectLoginPage = false;
  function request<Result, Param = unknown>(
    option: IRequestOption<IResponse<Result>, Param>
  ): Promise<Result | undefined> {
    const requestParams = { ...option };
    const {
      params = {},
      url,
      hideErrorToast = false,
      showSuccessToast = false,
    } = option;
    let serverUrl = url;
    if (!isExternal(url)) {
      requestParams.header = requestParams.header || {};
      requestParams.header["Authorization"] = CacheAuthrizedToken.get() || "";
      // requestParams.header["X-Client-Type"] = process.env.TARO_ENV;
      requestParams.header["X-Device-Type"] = "XCX"; // 小程序
      const baseUrl =
        option.enableMock && isDev ? config.mockBaseUrl : config.baseUrl;
      serverUrl = baseUrl + serverUrl;
    }
    const httpPath = queryString.stringifyUrl({
      url: serverUrl,
      query: params || {},
    });
    return uni.request<IResponse<Result>>({
      ...requestParams,
      timeout: 1000 * 10 * 60,
      url: httpPath,
    }).then(async (res: SuccessCallbackResult<IResponse<Result>>) => {
      const data = res.data;
      const msg = data.msg;
      if (!data && res.statusCode !== 200) {
        console.log("请求异常....", option, res);
        return Promise.reject(res.data);
      }
      if (data.code === 200) {
        if (showSuccessToast && msg) {
          await uni.showToast({ title: msg, icon: "none" });
        }
        return data.data;
      } else {
        if (!hideErrorToast && msg) {
          await uni.showToast({ title: msg, icon: "none" });
        }
        if (data.code === 401) {
          useAuthStore().logout();
          const instance = getCurrentInstance()
          const loginHomePath = ["/pages/home/index"];
          // @ts-ignore
          const isLoginPage = loginHomePath.includes(instance.page?.route);
          if (!isLoginPage && !isRedirectLoginPage) {
            isRedirectLoginPage = true;
            navigator.navigateTo({
              url: "/pages/home/index",
              complete() {
                isRedirectLoginPage = false;
              },
            });
          }
          return Promise.reject(res.data);
        }
      }
      console.log("请求异常....", option, res);
      return Promise.reject(res.data);
    });
  }
  export default request;
  